package binary_tree.leetcode.easy;

/**
 * @author bruin_du
 * @description 二叉搜索树的最近公共祖先
 * @date 2022/6/1 14:49
 **/
public class Offer68_LowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //方法一：递归
        recursion(root,p,q);

        //方法二：迭代
        return iteration(root,p,q);
    }

    private TreeNode iteration(TreeNode root, TreeNode p, TreeNode q) {
        while (root != null) {
            if (root.val < p.val && root.val < q.val) {
                root = root.right;
            } else if (root.val > p.val && root.val > q.val) {
                root = root.left;
            } else {
                break;
            }
        }
        return root;
    }

    private TreeNode recursion(TreeNode root, TreeNode p, TreeNode q) {
        if(p.val < root.val && q.val < root.val)
            return lowestCommonAncestor(root.left, p, q);
        if(p.val > root.val && q.val > root.val)
            return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}
